<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\CustomException;
use App\Http\Controllers\Controller;
use App\Models\Flow;
use App\Models\Message;
use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\Store;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Yansongda\LaravelPay\Facades\Pay;

//订单相关
class OrderController extends Controller
{

    /**
     * 创建订单初始化
     * @param Request $request
     * @return mixed
     */
    public function create_order_init(Request $request) {
        try {
            $validated_data = $this->validate($request, [
                'api_token'             =>  ['required', 'string'],
                'type'                  =>  'required|in:cart,order,product',
                //从购物车创建时
                'carts'                 =>  'required_if:type,cart|array',
                'carts.*'               =>  'required_if:type,cart|array',
                'carts.*.cart_id'       =>  'required_if:type,cart|int|gt:0',
                'carts.*.buynum'        =>  'required_if:type,cart|int|gt:0',
                //从待支付订单创建时
                'order_id'              =>  'required_if:type,order|int|gt:0',
                //从商品详情创建时
                'product'               =>  'required_if:type,product|array|size:3',
                'product.product_id'    =>  'required_with:product|int|gt:0',
                'product.sku_id'        =>  'required_with:product|int|gt:0',
                'product.buynum'        =>  'required_with:product|int|gt:0'
            ]);

            $order_model = new Order();
            $list = $order_model->create_order_init($validated_data);

            return $this->response(0, $list);
        }catch (CustomException $e) {
            return $this->response(0, [], $e->getMessage());
        }catch (\Exception $e) {
            Log::info($e);
            return $this->response(0, [], '创建订单初始化失败');
        }
    }


    //支付订单  todo    验证address_id、order_id是否是当前登陆人的  直接购买时扣除商品库存
    public function do_cash(Request $request) {
        try {
            $validated_data = $request->validate([
                'api_token'             =>  'required|string',
                'type'                  =>  'required|in:cart,order,product',
                //从购物车支付时
                'carts'                 =>  'required_if:type,cart|array',
                'carts.*'               =>  'required|array',
                'carts.*.cart_id'       =>  'required|int|gt:0',
                'carts.*.buynum'        =>  'required|int|gt:0',
                //从待支付订单创建时
                'order_id'              =>  'required_if:type, order|int|gt:0',
                //从商品详情创建时
                'product'               =>  'required_if:type,product|array|size:3',
                'product.product_id'    =>  'required_with:product|int|gt:0',
                'product.sku_id'        =>  'required_with:product|int|gt:0',
                'product.buynum'        =>  'required_with:product|int|gt:0',
                'address_id'            =>  'required_if:type,product,cart|int|gt:0',
                'remark'                =>  'nullable',
                'total_money'           =>  'required_if:type,product,cart|numeric|gt:0'
            ]);

            $order_model = new Order();
            //终端ip
            $client_ip = $request->getClientIp();
            return $this->response(0, $order_model->do_cash($validated_data, $client_ip));
        }catch (CustomException $e){
            Log::info("支付异常：");
            Log::info($e);

            return $this->response(1, [], $e->getMessage());
        }catch (\Exception $e) {
            Log::info("支付失败：");
            Log::info($e);

            return $this->response(1, [], '支付失败');
        }
    }

    //支付结果通知
    public function notify(Request $request) {
        $return = [];
        try {
            if ($request->isMethod('POST')) {
                $response = xml2arr(file_get_contents("php://input"));
                $return_code = $response['return_code'];
                if ($return_code == 'SUCCESS') {
                    //验证签名
                    $sign = $response['sign'];
                    unset($response['sign']);
                    $mp_controller = new MiniProgramController();
                    $new_sign = $mp_controller->sign($response);
                    if ($new_sign == $sign) {
                        //业务结果值:"SUCCESS"|"FAIL"
                        $result_code = $response['result_code'];
                        $openid = $response['openid'];
                        //微信支付订单号
                        $transaction_id = $response['transaction_id'];
                        //商户订单号，之前调用统一支付时生成的订单号。
                        $out_trade_no = $response['out_trade_no'];
                        //支付完成时间
                        $time_end = $response['time_end'];

                        //查询订单
                        $order = Order::with(['order_products' => function($query){
                            return $query->select('id', 'order_id', 'product_id', 'sku_id', 'buynum');
                        }])->where([
                            'openid'        =>  $openid,
                            'total_money'   =>  $response['total_fee'] / 100,
                            'no'            =>  $out_trade_no,
                            'status'        =>  NO_PAY
                        ])->first();

                        if ($order) {
                            //支付成功要给商品增加销量，失败通知不做处理
                            if ($result_code == 'SUCCESS') {
                                //增加规格销量
                                foreach ($order->order_products as $order_product) {
                                    ProductSku::where([
                                        'product_id'    =>  $order_product['product_id'],
                                        'id'            =>  $order_product['sku_id']
                                    ])->increment('real_sold_num', $order_product['buynum']);
                                    ProductSku::where([
                                        'product_id'    =>  $order_product['product_id'],
                                        'id'            =>  $order_product['sku_id']
                                    ])->increment('show_sold_num', $order_product['buynum']);
                                }
                                //todo  增加商品销量
                                $order->status = TO_DELIVERY;
                                $order->transaction_id = $transaction_id;
//                                $order->time_end = date('Y-m-d H:i:s',strtotime($time_end));
                                $order->time_end = Carbon::now();
                                $order->save();
                                $this->setMessage($order->id);
                            }
                        }
                        $return = ['return_code' => 'SUCCESS'];
                    }else {
                        $return = ['return_code' => 'FAIL','return_msg' => '签名验证失败'];
                    }
                }else {
                    $return = ['return_code' => 'FAIL','return_msg' => '通信失败'];
                }
            }
        }catch (CustomException $e) {
            Log::info('微信支付通知失败');
            Log::info($e);
            $return = ['return_code' => 'FAIL','return_msg' => '回调失败'];
        }
        return arr2xml($return);
    }

    /**
     * @param $id
     * 添加消息队列
     */
    public function setMessage($id)
    {
        $message = new Message();
        $message->order_id = $id;
        $message->save();
    }


    //订单详情
    function detail(Request $request) {
        $request->validate([
            'api_token' =>  'required|string',
            'id'        =>  'required|int|gt:0'
        ]);

        $user_model = new User();
        $user = $user_model->get_login_user($request->get('api_token'));
        $order_model = new Order();
        $where = [
            'id'        =>  $request->get('id'),
            'user_id'   =>  $user->id
        ];
        $order = $order_model->detail($request->get('id'), $user->id);

        return $this->response(0, $order);
    }

    //我的订单  todo  订单状态需要再次确认
    function my_order(Request $request) {
        $request->validate([
            'api_token' =>  'required|string',
            'status'    =>  ['nullable']
        ]);
        $user_model = new User();
        $user = $user_model->get_login_user($request->get('api_token'));
        $where['user_id'] = $user->id;
        if ($request->get('status')) {
            $where['status'] = $request->get('status');
        }

        $model = new Order();
        return $this->response(0, $model->get_orders($where,$request->get('limit')));
    }

    //核销订单  todo 小程序端用户是否具有核销资格的判断
    public function use_order(Request $request) {
        $request->validate([
            'order_id'  =>  'required',
            'api_token' =>  'required'
        ]);
        $order_id = $request->post('order_id');
        $order = Order::with(['product'=>function($query){
            return $query->select('id','hexiao_end','hexiao_mobile');
        }])->findOrFail($request->post('order_id'));

        //return $order->product->hexiao_end;
        //1、订单有效性
        if ($order->product->hexiao_end < date('Y-m-d H:i:s')) {
            return $this->response(1,[],'订单已经过期',['hexiao_end'=>['订单已经过期']]);
        }

        //核销工作人员信息
        $worker = User::where('api_token',$request->post('api_token'))->first();
        //2、核销人员是否有资格
        if (!$worker || $order->product->hexiao_mobile != $worker->mobile) {
            return $this->response(2,[],'没有权限',['hexiao_mobile'=>['没有权限']]);
        }

        $order->status = USED;
        $order->used_at = date('Y-m-d H:i:s');
        $order->save();

        return $this->response(0,[],'核销成功');
    }

    /**
     * 查询给类型订单数量
     * @param Request $request
     * @return JsonResponse
     */
    public function order_num_by_group(Request $request) {
        $request->validate([
            'api_token' =>  'required|string'
        ]);
        $user_model = new User();
        $user = $user_model->get_login_user($request->get('api_token'));

        $order_model = new Order();

        return $this->response(0, $order_model->order_num_by_group($user->id));
    }

    /**
     * 确认收货
     * @param Request $request
     * @return JsonResponse
     */
    public function receive(Request $request) {
        $request->validate([
            'api_token' =>  'required|string',
            'id'        =>  'required|int|gt:0'
        ]);

        $user_model = new User();
        $user = $user_model->get_login_user($request->post('api_token'));

        $order_model = new Order();
        $order_model->receive($request->post('id'), $user->id);

        return $this->response(0);
    }


    /**
     * 评价订单
     * @param Request $request
     * @return JsonResponse
     */
    public function comment(Request $request) {
        $request->validate([
            'api_token' =>  'required|string',
            'id'        =>  'required|int|gt:0',
            'content'   =>  'required|string|max:255'
        ]);

        $user_model = new User();
        $user = $user_model->get_login_user($request->post('api_token'));

        $order_model = new Order();
        $order_model->comment($request->post('id'), $user->id, $request->post('content'));

        return $this->response(0);
    }



    /**
     * @return string|\Symfony\Component\HttpFoundation\Response
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * 退款验证
     */
    public function refundNotify()
    {
        $config = config('pay.wechat');
        $pay = Pay::wechat($config);
        $data = $pay->verify(null, true); // 是的，验签就这么简单

        if (!$data) {
            return '';
        }
        $orderData = Order::where(['order_no'=>$data['out_trade_no'],'out_refund_no'=>$data['out_refund_no'],'pay_status'=>1,'refund_status'=>0])->first();
        if ($data['return_code'] === 'SUCCESS' && $orderData) {
            if (($orderData->pay_status == 1) && ($orderData->status == 1)) {
                $orderData->update([
                    'pay_status' => -1,
                    'status' => 1,
                    'refund_status' => 1
                ]);
                $openid = $orderData->openid;
                if($openid) {
                    $this->sendRefundTemplate($openid, $orderData->pay_money);
                }
                return $pay->success();
            }
            return '';
        }
        return '';
    }

}
